package rs;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import rs.util.TimeUtil;

public class Timer {
	
	public static HashMap<String, Long> timestamp = new HashMap<String, Long>();
	
	public static long delayOf(String url){
		try {
			URL u = new URL(url);
			String host = u.getHost();
			long now = TimeUtil.now();
			//如果首次执行,则立即执行.
			if(null == timestamp.get(host)){
				timestamp.put(host, now);
				return 0;
			} else {
				long t = timestamp.get(host);
				long when = now;
				int delay = Conf.SAME_HOST_DELAY;
				//如果上次时间距今超过delay,则立即执行.
				if(now - t > delay){
					timestamp.put(host, when);
					return 0;
				}
				//否则,将在上次执行时间的delay毫秒后执行.
				when = t + delay;
				timestamp.put(host, when);
				return when - now;
			}
		} catch (MalformedURLException e) {
			System.err.println("URL: " + url);
			e.printStackTrace();
		}
		return 0;
	}

}
